﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class Auth_Default : System.Web.UI.Page, IHistoryPage
{
	public Stack<ControlContainer> HistoryBackward
	{
		get
		{
			if (this.Session["historyBackward"] == null)
			{
				this.Session["historyBackward"] = new Stack<ControlContainer>();
			}
			return this.Session["historyBackward"] as Stack<ControlContainer>;
		}
	}

	public ControlContainer CurrentControl
	{
		get
		{
			return this.Session["currentControl"] as ControlContainer;
		}
		set
		{
			this.Session["currentControl"] = value;
		}
	}

	public Stack<ControlContainer> HistoryForward
	{
		get
		{
			if (this.Session["historyForward"] == null)
			{
				this.Session["historyForward"] = new Stack<ControlContainer>();
			}
			return this.Session["historyForward"] as Stack<ControlContainer>;
		}
	}

	protected void Page_Init(object sender, EventArgs e)
	{
	}

	protected override void CreateChildControls()
	{
		base.CreateChildControls();
		if (this.CurrentControl == null)
		{
			this.CurrentControl = new ControlContainer();
			this.CurrentControl.UserControlPath = "~/Auth/Default.ascx";
			this.CurrentControl.Title = "Principal";
		}
		ReloadCurrentControl();
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			switch (this.Session["usuarioTipo"].ToString())
			{
				case "A":
					BuildAdminMenu();
					break;
				case "O":
					BuildUserMenu();
					break;
			}
		}
	}

	private void BuildUserMenu()
	{
		this.Menu1.Items.AddAt(0, new MenuItem(" Cadastros", string.Empty, "~/images/folder.png"));
		this.Menu1.Items[0].ChildItems.AddAt(0, new MenuItem("Ativo", "~/Auth/Ativos.ascx"));
		this.Menu1.Items.AddAt(1, new MenuItem(" Realizar Consulta", "~/Auth/RealizarConsulta.ascx", "~/images/search.png"));
		this.Menu1.Items.AddAt(2, new MenuItem(" Registrar Leitura", "~/Auth/RegistrarLeitura.ascx", "~/images/tasks.png"));
	}

	private void BuildAdminMenu()
	{
		this.Menu1.Items.AddAt(0, new MenuItem(" Cadastros", string.Empty, "~/images/folder.png"));
		this.Menu1.Items[0].ChildItems.Add(new MenuItem("Campo", "~/Auth/Campos.ascx"));
		this.Menu1.Items[0].ChildItems.Add(new MenuItem("Fabricante", "~/Auth/FabricantesAtivos.ascx"));
		this.Menu1.Items[0].ChildItems.Add(new MenuItem("Local de Armazenagem", "~/Auth/LocaisArmazenagem.ascx"));
		this.Menu1.Items[0].ChildItems.Add(new MenuItem("Portal RFID", "~/Auth/PortaisLeitoresRFID.ascx"));
		this.Menu1.Items[0].ChildItems.Add(new MenuItem("Tipo de Ativo", "~/Auth/TiposAtivos.ascx"));
		this.Menu1.Items[0].ChildItems.Add(new MenuItem("Usuário", "~/Auth/Usuarios.ascx"));
	}

	public Control ChangeCurrentControlTo(string path)
	{
		this.HistoryForward.Clear();

		if (this.CurrentControl != null)
		{
			this.HistoryBackward.Push(this.CurrentControl);
			CurrentControl.SaveViewState();
		}
		CurrentControl = new ControlContainer();
		CurrentControl.UserControlPath = path;
		RealodHistory();
		return ReloadCurrentControl();
	}

	private void RealodHistory()
	{
		int maxHistoryCount = int.Parse(ConfigurationSettings.AppSettings["MaxHistoryCount"]);

		if (this.HistoryBackward.Count > maxHistoryCount)
		{
			ControlContainer[] histBack = this.HistoryBackward.ToArray();

			this.HistoryBackward.Clear();

			for (int i = maxHistoryCount - 1; i > -1; i--)
			{
				this.HistoryBackward.Push(histBack[i]);
			}
		}

		if (this.HistoryForward.Count > maxHistoryCount)
		{
			ControlContainer[] histFor = this.HistoryForward.ToArray();

			this.HistoryForward.Clear();

			for (int i = maxHistoryCount - 1; i > -1; i--)
			{
				this.HistoryForward.Push(histFor[i]);
			}
		}

		{
			MenuItem menuHistBack = this.Menu1.FindItem("Backward");
			menuHistBack.ChildItems.Clear();

			menuHistBack.Enabled = this.HistoryBackward.Count > 0;

			ControlContainer[] histBack = this.HistoryBackward.ToArray();

			for (int i = 0; i < histBack.Length; i++)
			{
				MenuItem histMenuItem = new MenuItem();
				histMenuItem.Text = histBack[i].Title;
				histMenuItem.Value = "Backward_" + i;

				menuHistBack.ChildItems.Add(histMenuItem);
			}
		}

		{
			MenuItem menuHistFor = this.Menu1.FindItem("Forward");
			menuHistFor.ChildItems.Clear();

			menuHistFor.Enabled = this.HistoryForward.Count > 0;

			ControlContainer[] histFor = this.HistoryForward.ToArray();

			for (int i = 0; i < histFor.Length; i++)
			{
				MenuItem histMenuItem = new MenuItem();
				histMenuItem.Text = histFor[i].Title;
				histMenuItem.Value = "Forward_" + i;

				menuHistFor.ChildItems.Add(histMenuItem);
			}
		}

		this.Menu1.FindItem("Backward").Enabled = this.HistoryBackward.Count > 0;
	}

	private Control ReloadCurrentControl()
	{
		this.ControlPlaceHolder.Controls.Clear();
		this.CurrentControl.Instance = LoadControl(CurrentControl.UserControlPath);
		this.CurrentControl.Instance.ID = "loaded";
		this.ControlPlaceHolder.Controls.Add(this.CurrentControl.Instance);
		
		if (String.IsNullOrEmpty(this.CurrentControl.Title))
		{
			Label lblTitle = this.CurrentControl.Instance.FindControl("lblTitle") as Label;
			CurrentControl.Title = lblTitle.Text;
		}
		CurrentControl.LoadViewState();

		return this.CurrentControl.Instance;
	}

	public Control GoBackHistory(int count)
	{
		if (this.HistoryBackward.Count > 0)
		{
			this.HistoryForward.Push(this.CurrentControl);

			for (int i = 0; i < count && HistoryBackward.Count > 0; i++)
			{
				this.HistoryForward.Push(this.HistoryBackward.Pop());
			}

			CurrentControl.SaveViewState();
			this.CurrentControl = this.HistoryBackward.Pop();
			RealodHistory();
			return ReloadCurrentControl();
		}
		else if (this.ControlPlaceHolder.Controls.Count > 0)
		{
			return ControlPlaceHolder.Controls[0];
		}
		else return null;
	}

	public Control GoForwardHistory(int count)
	{
		if (this.HistoryForward.Count > 0)
		{
			this.HistoryBackward.Push(this.CurrentControl);

			for (int i = 0; i < count && HistoryForward.Count > 0; i++)
			{
				this.HistoryBackward.Push(this.HistoryForward.Pop());
			}

			CurrentControl.SaveViewState();
			this.CurrentControl = this.HistoryForward.Pop();
			RealodHistory();
			return ReloadCurrentControl();
		}
		else if (this.ControlPlaceHolder.Controls.Count > 0)
		{
			return ControlPlaceHolder.Controls[0];
		}
		else return null;
	}

	protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
	{
		if (e.Item.Value.StartsWith("Forward"))
		{
			int count = 0;
			if (e.Item.Value.Contains('_'))
			{
				count = int.Parse(e.Item.Value.Split('_')[1]);
			}

			GoForwardHistory(count);
		}
		else if (e.Item.Value.StartsWith("Backward"))
		{
			int count = 0;
			if (e.Item.Value.Contains('_'))
			{
				count = int.Parse(e.Item.Value.Split('_')[1]);
			}

			GoBackHistory(count);
		}
		else if (e.Item.Value.Equals("Sair"))
		{
			Session.Abandon();
			FormsAuthentication.SignOut();
			FormsAuthentication.RedirectToLoginPage();
		}
		else if (!string.IsNullOrEmpty(e.Item.Value))
		{
			ChangeCurrentControlTo(e.Item.Value);
		}
	}
}
